﻿
using Ec.NETCoreFramework.Common;
using Ec.NETCoreFramework.Common.Core.Helpers;
using Ec.NETCoreFramework.Common.Core.Serializer;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Ec.NETCoreFramework.Common.Cache
{
    /// <summary>
    /// redis操作
    /// </summary>
    public class RedisDataBaseManager: IDisposable
    {
        /// <summary>
        /// 默认超时时间（单位秒）
        /// </summary>
        int DEFAULT_TMEOUT = 10;
        /// <summary>
        /// database
        /// </summary>
        protected IDatabase _Database;

        protected IServer _Server;

        string _serverLocal = "";
        int _DatabaseId = 0;

        ConnectionMultiplexer _Multiplexer = null;

        static readonly object _locker = new object();

        /// <summary>
        /// Initializes a new instance of the <see cref="StackExchangeRedisService"/> class.
        /// </summary>
        /// <param name="server">服务器信息.</param>
        /// <param name="password">密码.</param>
        /// <param name="dbId">数据库Id.</param>
        public RedisDataBaseManager(string server, string password, int dbId)
        {
            try
            {
                lock (_locker)
                {
                    _serverLocal = server;
                    _DatabaseId = dbId;
                    _Multiplexer = StackExchangeManager.GetMultiplexer(server, password);
                    if (_Multiplexer != null && _Multiplexer.IsConnected)
                    {
                        _Server = _Multiplexer.GetServer(server);
                        _Database = _Multiplexer.GetDatabase(dbId);
                    }
                }
            }
            catch (Exception ex)
            {
                LoggerHelper.Instance.Error("Cache-Redis" + ex.Message);
            }
        }

        /// <summary>
        /// 连接超时设置
        /// </summary>
        public int TimeOut
        {
            get
            {
                return DEFAULT_TMEOUT;
            }
            set
            {
                DEFAULT_TMEOUT = value;
            }
        }

        /// <summary>
        /// 获取缓存中所有的key
        /// </summary>
        public string[] Keys
        {
            get
            {
                List<string> all_keys = new List<string>();
                if (_Database == null) return all_keys.ToArray();
                // 清除Redis指字的数据库keys
                // if (_Server != null) _Server.FlushDatabase(_Database.Database); 此模式不允许在非admin模式下使用
                var keys = _Server.Keys(_Database.Database);
                foreach (var key in keys)
                {
                    all_keys.Add(key.ToString());
                }
                return all_keys.ToArray();
            }
        }

        public string Info
        {
            get { return "Redis Cache: " + _serverLocal + "[" + _DatabaseId.ToString() + "]"; }
        }
        private bool _disposed = false;
        protected virtual void Dispose(bool disposing)
        {
            if (!this._disposed)
            {
                if (disposing)
                {
                    _Multiplexer.Dispose();
                    _Multiplexer = null;
                }
            }
            this._disposed = true;
        }
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}
